package com.kfm.controller;

import com.kfm.domain.User;
import com.kfm.domain.groups.LoginGroup;
import com.kfm.ex.ServiceException;
import com.kfm.service.UserService;
import com.kfm.util.Contains;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping({"/login", "/"})
    public ModelAndView toLogin(){
        return new ModelAndView("login");
    }

    @PostMapping("/login")
    public ModelAndView login(ModelAndView mv, String captcha, @Validated(LoginGroup.class) User user, Errors errors, HttpSession session
                              , HttpServletRequest request) {
        if (errors.hasErrors()){
            throw new ServiceException("用户名或密码不能为空");
        }

        if (!CaptchaUtil.ver(captcha, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            mv.addObject("msg", "验证码错误，请重新输入");
            mv.setViewName("login");

        } else {
            User login = userService.login(user);

            if (login != null){
                // 登录成功
                session.setAttribute(Contains.LOGIN_USER, login);
                mv.setViewName("redirect:index");
            } else {
                mv.addObject("msg", "登录失败，用户名或密码不正确");
                mv.setViewName("login");
            }
        }
        return mv;
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }

    @GetMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("index");
    }
}
